from typing import Any

from django import forms
from django.contrib.auth import get_user_model

User = get_user_model()


class UserCreateForm(forms.ModelForm):
    password1 = forms.CharField(label="密码", widget=forms.PasswordInput)
    password2 = forms.CharField(label="确认密码", widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = ["username", "email", "is_staff", "is_superuser", "is_active"]

    def clean(self) -> dict[str, Any]:
        cleaned = super().clean()
        p1 = cleaned.get("password1")
        p2 = cleaned.get("password2")
        if p1 and p2 and p1 != p2:
            self.add_error("password2", "两次输入的密码不一致")
        return cleaned

    def save(self, commit: bool = True) -> User:
        user: User = super().save(commit=False)
        password = self.cleaned_data.get("password1")
        if password:
            user.set_password(password)
        if commit:
            user.save()
        return user


class UserUpdateForm(forms.ModelForm):
    # 添加Profile模型的字段
    avatar = forms.ImageField(label="头像", required=False, widget=forms.ClearableFileInput)
    phone = forms.CharField(label="手机号", max_length=15, required=False)

    class Meta:
        model = User
        fields = ["username", "email", "first_name", "last_name", "is_staff", "is_superuser", "is_active"]
        widgets = {
            "username": forms.TextInput(attrs={"disabled": "disabled"})
        }

    def __init__(self, *args, **kwargs):
        # 初始化表单时，从Profile加载头像和电话
        super().__init__(*args, **kwargs)
        if self.instance and hasattr(self.instance, 'profile'):
            self.fields['avatar'].initial = self.instance.profile.avatar
            self.fields['phone'].initial = self.instance.profile.phone

    def save(self, commit=True):
        # 先保存User模型
        user = super().save(commit=commit)
        
        # 再保存Profile模型
        if commit and hasattr(self.instance, 'profile'):
            profile = user.profile
            if 'avatar' in self.cleaned_data:
                avatar = self.cleaned_data['avatar']
                if avatar is False:  # ClearableFileInput返回False表示删除
                    profile.avatar = None
                elif avatar:  # 如果提供了新头像
                    profile.avatar = avatar
            
            if 'phone' in self.cleaned_data:
                profile.phone = self.cleaned_data['phone']
            
            profile.save()
        
        return user


